<template>
  <div class="assessment-detail-container">
    <el-card class="main-content" shadow="never" v-loading="loading">
      <div class="header-row">
        <el-button @click="goBack" icon="el-icon-arrow-left" size="large">返回</el-button>
        <el-button @click="finish" icon="el-icon-arrow-left" size="large">完成评分</el-button>
        <span class="page-title">员工考核详情</span>
      </div>

      <el-steps :active="stepActive" align-center class="steps-bar" finish-status="success">
        <el-step title="待评分" description="等待评分开始" />
        <el-step title="评分中" description="正在进行评分" />
        <el-step title="评分完成" description="评分已完成" />
      </el-steps>

      <div class="user-info">
        <el-avatar :size="80" :src="avatarUrl" @error="handleAvatarError" />
        <div class="user-name">{{ employeeName }}</div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">考核计划：</span>
            <span class="value">{{ data.planName || '未知' }}</span>
          </div>
          <div class="info-item">
            <span class="label">考核周期：</span>
            <span class="value">{{ data.cycle || '未知' }}</span>
          </div>
          <div class="info-item">
            <span class="label">最终得分：</span>
            <span class="value score" :class="{ 'has-score': data.finalScore !== null }">
              {{ data.finalScore ?? '未评分' }}
            </span>
          </div>
        </div>
      </div>

      <el-tabs v-model="activeTab" class="mt-2">
        <el-tab-pane label="指标评分明细" name="score">
          <el-skeleton :rows="5" :loading="loading" animated>
            <template v-if="data.types.length">
              <div v-for="(item, index) in data.types" :key="item.indicatorsTypeId" class="indicator-section">
                <div class="table-title">
                  <el-icon>
                    <Document />
                  </el-icon>
                  {{ item.typeName }}
                </div>
                <el-table :data="item.indicators || []" border stripe :row-class-name="getRowClassName">
                  <el-table-column prop="indicatorsName" label="指标名称" min-width="200" />
                  <el-table-column prop="indicatorsRule" label="指标规则" min-width="300" show-overflow-tooltip />
                  <el-table-column label="开始评分" width="120" align="center">
                    <template #default="{ row }">
                      <el-button type="primary" :disabled="stepActive==3?true:false" size="small" @click="goToScore(row)">
                        开始评分
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column prop="indicatorsScore" label="评分" width="120" align="center">
                    <template #default="{ row }">
                      <el-tag :type="getScoreTagType(row.indicatorsScore)" size="small">
                        {{ row.indicatorsScore ?? '未评分' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
            <el-empty v-else description="暂无指标数据" />
          </el-skeleton>
        </el-tab-pane>
      </el-tabs>
    </el-card>


    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
    <el-input-number v-model="selectedIndicatorScore" :min="0" :max="selectedIndicatorMaxScore" placeholder="请输入最大分数" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateIndicatorScore()">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { get } from '@/api/jixiao/assessmentProgress/employeeAccessDetail/employeeAccessDetail.js';
import { ElMessage } from 'element-plus';
import { Document } from '@element-plus/icons-vue';
import { updateStatus, addScore, getIndicatorInfo ,updateFinalScore} from '@/api/jixiao/assessmentProgress/employeeAccessDetail/employeeAccessDetail.js';

const route = useRoute();
const router = useRouter();
const activeTab = ref('score');
const data = ref({
  types: [],
  planName: '',
  cycle: '',
  finalScore: null,
  assessmentStatus: null
});
const dialogFormVisible = ref(false);
const employeeName = ref(route.query.employeeName || '未知员工');
const assessmentStatus = ref(route.query.assessmentStatus || '待评分');
const loading = ref(true);
const stepActive = ref(1);
const isMounted = ref(true);

// 计算头像URL
const avatarUrl = computed(() => {
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(employeeName.value)}`;
});
const employeeId = ref(route.query.id);
const selectedIndicator = ref();
const selectedIndicatorMaxScore = ref(0);
const selectedIndicatorScore = ref(0);
function goToScore(row) {
  //  console.log(row.indicatorsId) 
  selectedIndicator.value = row.indicatorsId;
  console.log('选中的指标id:' + selectedIndicator.value)
  console.log('当前员工id:' + employeeId.value)

  getIndicatorInfo(selectedIndicator.value).then((res) => {
    // console.log(res)
    selectedIndicatorMaxScore.value = res.data.scoreMaxline;
    // console.log('当前指标最大分数:' + selectedIndicatorMaxScore.value)
  })
  dialogFormVisible.value = true;



  updateStatus({
    employeeId: employeeId.value,
    status: '考核中'
  }).then(() => {
    ElMessage.success('状态更新成功');
    stepActive.value = 2; // 更新步骤状态

  }).catch(error => {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  });

}

function finish() {
    updateStatus({
    employeeId: employeeId.value,
    status: '已完成'
  }).then(() => {
    ElMessage.success('状态更新成功');
    stepActive.value = 3; // 更新步骤状态

  }).catch(error => {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  });

updateFinalScoreData()
}
async function updateFinalScoreData(){
  //更新总的分数
  console.log('最终分数:'+ data.value.finalScore)
  await updateFinalScore({
    employeeId: employeeId.value,
    finalScore: data.value.finalScore 
  })
}
// 
async function updateIndicatorScore() {
  dialogFormVisible.value = false;
  console.log('当前指标id:' + selectedIndicator.value);
  console.log('当前员工id:' + employeeId.value);
  console.log('当前指标分数:' + selectedIndicatorScore.value);

  await addScore({
    employeeId: employeeId.value,
    indicatorsId: selectedIndicator.value,
    score: selectedIndicatorScore.value
  }).then(async () => {
    ElMessage.success('评分成功');
    dialogFormVisible.value = false;
    await fetchData();
    await updateFinalScoreData();
  }).catch(error => {
    console.error('评分失败:', error);
    ElMessage.error('评分失败');
  });
}

// 更新步骤状态
function updateStepActive(status) {
  const statusMap = {
    '考核中': 2,
    '已完成': 3,
    '待评分': 1
  };
  stepActive.value = statusMap[status] || 1;
}

// 获取行样式
function getRowClassName({ row }) {
  return row.indicatorsScore === null ? 'unscored-row' : '';
}

// 获取分数标签类型
function getScoreTagType(score) {
  if (score === null) return 'info';
  if (score >= 90) return 'success';
  if (score >= 60) return 'warning';
  return 'danger';
}

// 处理头像加载错误
function handleAvatarError() {
  console.warn('Avatar failed to load');
}

// 获取数据
async function fetchData() {
  if (!route.query.id) {
    ElMessage.error('缺少员工ID');
    loading.value = false;
    return;
  }

  loading.value = true;
  try {
    const res = await get({ employeeId: route.query.id });
    if (!isMounted.value) return;

    data.value = { ...res, types: res.types || [] };
    updateStepActive(route.query.assessmentStatus);
    ElMessage.success('数据加载成功');
  } catch (error) {
    if (!isMounted.value) return;
    console.error('加载失败:', error);
    ElMessage.error(error.message || '数据加载失败');
  } finally {
    loading.value = false;
  }
}

function goBack() {
  router.back();
}

onMounted(() => {
  fetchData();
});

onUnmounted(() => {
  isMounted.value = false;
});
</script>

<style scoped>
.assessment-detail-container {
  display: flex;
  gap: 24px;
  padding: 32px 24px;
  background: #f7f8fa;
  min-height: 100vh;
}

.main-content {
  flex: 1.8;
  padding: 32px;
  border-radius: 12px;
  background: #fff;
  min-width: 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header-row {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-left: 8px;
  color: #303133;
}

.steps-bar {
  margin: 24px 0 32px 0;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 8px;
}

.user-name {
  font-size: 22px;
  font-weight: 600;
  margin: 16px 0 8px 0;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  width: 100%;
  margin-top: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #606266;
  font-size: 14px;
}

.value {
  color: #303133;
  font-weight: 500;
}

.value.score {
  font-size: 18px;
  font-weight: 600;
  color: #909399;
}

.value.score.has-score {
  color: #67c23a;
}

.mt-2 {
  margin-top: 16px;
}

.indicator-section {
  margin-bottom: 32px;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  margin: 24px 0 16px 0;
  color: #303133;
}

:deep(.unscored-row) {
  background-color: #fafafa;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

@media (max-width: 768px) {
  .assessment-detail-container {
    padding: 16px;
  }

  .main-content {
    padding: 16px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .header-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .page-title {
    margin-left: 0;
  }
}
</style>